package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.xxxx.server.mapper.PositionMapper;
import com.xxxx.server.pojo.Position;
import com.xxxx.server.service.IPositionService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements IPositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean save(Position position) {
        checkParam(position);
        position.setCreateDate(LocalDateTime.now());
        position.setEnabled(true);
        removeCache();
        return SqlHelper.retBool(getBaseMapper().insert(position));
    }

    @Override
    public boolean updateById(Position position) {
       checkParam(position);
       System.out.println("update...");
       removeCache();
       return SqlHelper.retBool(getBaseMapper().updateById(position));
    }

    @Override
    public boolean removeById(Serializable id) {
        Assert.notNull(positionMapper.selectOne(new QueryWrapper<Position>()
                .eq("id",id)),"该记录不存在");
        return SqlHelper.retBool(getBaseMapper().deleteById(id));
    }

    public void checkParam(Position position){
        Assert.notNull(position,"职位不能为空");

        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        if(position.getId() != null){
            wrapper.eq("id",position.getId());
            Assert.notNull( positionMapper.selectOne(wrapper),"该记录不存在");
            return;
        }
        wrapper.eq("name",position.getName());
        Position one = positionMapper.selectOne(wrapper);
        Assert.isTrue( one == null,"该职位已存在");
    }

    public void removeCache(){
       redisTemplate.delete("positions");
    }

    @Override
    public List<Position> getAll() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<Position> positions = ((List<Position>) ops.get("positions"));
        if(Collections.isEmpty(positions)){
            positions = this.list();
            ops.set("positions",positions);
        }
        return positions;
    }
}
